package com.tobearc.persist.server;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.tobearc.persist.http.HttpServerCodec;


/**
 * 
 * @author yangqifan
 */
public class HTTPServer implements IServer {
	
	 /** Choose your favorite port number. */
    private static final int PORT = 1234;

    /** Set this to true if you want to make the server SSL */
    private static final boolean USE_SSL = false;

	public boolean init(){
		try {
			NioSocketAcceptor acceptor = new NioSocketAcceptor();
			acceptor.getSessionConfig().setReceiveBufferSize(1024*10);
			DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
//			MdcInjectionFilter mdcInjectionFilter = new MdcInjectionFilter();
//			chain.addLast("mdc", mdcInjectionFilter);
	
			// Add SSL filter if SSL is enabled.
			if (USE_SSL) {
			    addSSLSupport(chain);
			}
	
			chain.addLast("codec", new HttpServerCodec());
	
			addLogger(chain);
	
			// Bind
			acceptor.setHandler(new ChatProtocolHandler());
			acceptor.bind(new InetSocketAddress(PORT));
	
			System.out.println("Listening on port " + PORT); 
			} catch (Exception e) {
				// TODO: handle exception
			}
		return true;
	}

	public boolean start() {
		return false;
	}

	public boolean stop() {
		return false;
	}

    private static void addSSLSupport(DefaultIoFilterChainBuilder chain)
            throws Exception {
    }

    private static void addLogger(DefaultIoFilterChainBuilder chain)
            throws Exception {
        chain.addLast("logger", new LoggingFilter());
        System.out.println("Logging ON");
    }
    
    public static void main(String[] args) {
    	HTTPServer httpServer = new HTTPServer();
		httpServer.init();
	}
}
